#include "uart2.h"
#include "stdlib.h"
#include "string.h"

xdata u16 uart2_rx_sta; // bit15用于标志是否已接受到一个完整的数据包,bit[14:0]用于存储当前数据包的长度
xdata u8 uart2_buf[UART2_PACKET_MAX_LEN];
u8 uart2_step = 0;
static u8 data_len;
static u16 recv_len;
static u8 check_code;
static u8 rx_ok = 0;

extern u16 rxTimeCnt;
#if (UART2_INT_EN)	
//串口2中断服务程序
//发送数据时,必须关闭中断,这里只负责处理接受中断
void uart2_isr() interrupt 4
{
	xdata u8 res;

	if (RI0) //是串口接受中断
	{
		RI0 = 0;	 //清除接受中断标志
		res = SBUF0; //读取串口数据
		uart2_buf[recv_len] = res;
		// if (uart2_buf[recv_len - 2] == 0x62 && uart2_buf[recv_len - 1] == 0x6c && uart2_buf[recv_len] == 0x6d && recv_len > 1)
		// {
		// 	step = 1;
		// }
		// if (step)
		// {
		// 	if (uart2_buf[recv_len - 4] == 0x6d && uart2_buf[recv_len - 3] == 0x6c && uart2_buf[recv_len-2] == 0x62)
		// 	{
		// 		rx_ok = 1;
		// 	}
		// }
		recv_len++;
		if (recv_len >= UART2_PACKET_MAX_LEN)
		{
			uart2_step = 0;
			recv_len = 0;
		}
		rxTimeCnt = 0;
		if(uart2_step == 0)
		{
			uart2_step = 1;
		}
	}
}
#endif
u8 get_recv_flag(void)
{
	return rx_ok;
}
void clr_recv_flag(void)
{
	rx_ok = 0;
}

void uart2_run(void)
{
	if(rxTimeCnt >= 15)
	{
		uart2_step = 0;
		rxTimeCnt = 0;
		rx_ok = 1;
	}
}
u8 *get_recvBufPointer(void)
{
	return uart2_buf;
}

u16 get_recv_dataLen(void)
{
	return recv_len;
}

void recv_restart(void)
{
	rx_ok = 0;
	recv_len = 0;
	memset(uart2_buf, 0, sizeof(uart2_buf));
}
//串口2初始化
void uart2_init(u32 baud)
{
	MUX_SEL |= 0x40; // bit6置1表示将uart2接口引出到P0.4和P0.5
	P0MDOUT &= 0xCF;
	P0MDOUT |= 0x10; //设置对应的IO口输出输入
	ADCON = 0x80;	 //选择SREL0H:L作为波特率发生器
	SCON0 = 0x50;	 //接受使能和模式设置
	PCON &= 0x7F;	 // SMOD=0
	//波特率设置,公式为:
	// SMOD=0  SREL0H:L=1024-主频/(64*波特率),SMOD=1	 SREL0H:L=1024-主频/(32*波特率)
	baud = 1024 - (u16)(3225600.0f / baud);
	SREL0H = (baud >> 8) & 0xff;
	SREL0L = baud & 0xff;

#if (UART2_INT_EN)
	ES0 = 1; //中断使能
	EA = 1;
	// xdata变量都得在函数中初始化
	uart2_rx_sta = 0;
	uart2_step = 0;
#else
	ES0 = 0;
#endif
}

//发送一个字节
void u2_send_byte(u8 byte)
{
	ES0 = 0; //先关闭串口2中断
	SBUF0 = byte;
	while (!TI0)
		;
	TI0 = 0;
#if (UART2_INT_EN)
	ES0 = 1; //再打开中断
#endif
}

//发送数据
void u2_send_bytes(u8 *bytes, u16 len)
{
	xdata u16 i;

	ES0 = 0; //先关闭串口2中断
	if (len >= UART2_PACKET_MAX_LEN)
	{
		mprintf ("cross_border\r");
		len = UART2_PACKET_MAX_LEN;
	}
	for (i = 0; i < len; i++)
	{
		SBUF0 = bytes[i];
		while (!TI0)
			;
		TI0 = 0;
	}
#if (UART2_INT_EN)
	ES0 = 1; //再打开中断
#endif
}

//用uart2串口实现printf函数
char putchar(char c)
{
	u2_send_byte(c);

	return c;
}
